//
//  ClubeShowTableViewController.m
//  MagazineShangejie
//
//  Created by cnbizMedia on 15/9/14.
//  Copyright (c) 2015年 CnbizMedia. All rights reserved.
//

#import "ClubeShowTableViewController.h"
#import "Util.h"

@interface ClubeShowTableViewController (){
    NSMutableDictionary*dic_m;
 
    UIView*headerView;
    NSMutableArray*headerButtons;
    NSMutableArray*userData;
    
    BOOL isLoading;//是否在刷新
    BOOL reloading;
    
    int _page;

    NSDictionary *parameter;
}

@property(nonatomic,strong)EGORefreshTableHeaderView * refreshHeaderView;

@end

@implementation ClubeShowTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"[_scrollAnchorView.frame.origin.y ]%@",self.navigationController ) ;
    
    _page = 1;
    
    
    [SVProgressHUD showWithStatus:@"数据加载中..." maskType:SVProgressHUDMaskTypeClear];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tableView.backgroundColor=UIColorFromRGB(0xf5f5f5);
    userData = [[NSMutableArray alloc] init];
 
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.frame=CGRectMake (0,0,self.view.frame.size.width,self.view.frame.size.height-49);
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    parameter = [[NSDictionary alloc]init];
    
    
    UIButton *buttonf=[UIButton buttonWithType:UIButtonTypeCustom];
    [buttonf setFrame:CGRectMake(0, 0, 22, 22)];
    [buttonf addTarget:self action:@selector(popOfDismss) forControlEvents:UIControlEventTouchUpInside];
    [buttonf setImage:[UIImage imageNamed:@"dismiss"] forState:UIControlStateNormal];
    
    NSString *whereComeForm = [UserDefaults objectForKey:@"whereComeForm"];
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
        //状态栏的文字颜色换成白色
        //        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        
        if ([whereComeForm isEqualToString:@"clube"]) {
            //            [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
            [buttonf setImage:[UIImage imageNamed:@"dismissGray"] forState:UIControlStateNormal];
        }
        
    }
     
    
    UIBarButtonItem*leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:buttonf];
    self.navigationItem.leftBarButtonItem=leftBarItem;
    ////添加返回手势
//    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
//    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
//    [[self view] addGestureRecognizer:recognizer];
    
    
    
    EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(self.tableView.frame.origin.x,self.tableView.frame.origin.y, self.tableView.frame.size.width, 0)];
    view.delegate = self;
    [self.tableView addSubview:view];
    
    self.refreshHeaderView = view;
    [self loadNews];
}


-(void)loadNews{
    if(isLoading){
        [SVProgressHUD dismiss];
        return;
    }
    
    isLoading = YES;
//    NSDictionary*parameter;
//    if (_page==1) {
//        parameter=@{@"p":[NSString stringWithFormat:@"%d",_page],@"top":@"1",@"ps":@"20"};
//    }else{
//        parameter=@{@"p":[NSString stringWithFormat:@"%d",_page],@"ps":@"20"};
//    }
    
    //2. 取出数据
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSInteger number = [userDefault integerForKey:@"buttonTagNumber"];

    switch (number) {
        case 0:
            self.title = @"论坛";
            parameter=@{@"p":[NSString stringWithFormat:@"%d",_page],@"slug":@"luntan",@"p":@"1",@"ps":@"20"};//slug=luntan&p=1
            break;
            
        case 1:
            self.title = @"游学";
            parameter=@{@"p":[NSString stringWithFormat:@"%d",_page],@"slug":@"youxue",@"p":@"1",@"ps":@"20"};//slug=luntan&p=1
            break;
            
        case 2:
            self.title = @"咨询";
            parameter=@{@"p":[NSString stringWithFormat:@"%d",_page],@"slug":@"zixun",@"p":@"1",@"ps":@"20"};//slug=luntan&p=1
            break;
            
        case 3:
            self.title = @"创投";
            parameter=@{@"p":[NSString stringWithFormat:@"%d",_page],@"slug":@"chuangtou",@"p":@"1",@"ps":@"20"};//slug=luntan&p=1
            break;
            
        default:
            break;
    }


    [[AppAPIClient sharedClient] GET:@"Club/List" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *result = responseObject[@"data"];
        NSLog(@"luntan-data == %@",result);
        if([result isKindOfClass:[NSNull class]] || [result count] == 0){
            return;
        }
        if([result isKindOfClass:[NSNull class]] || [result count] == 0||[result[@"content"] count]==0){
            return;
        }
        if(userData == nil){
            userData = [[NSMutableArray alloc]initWithArray:result[@"content"] copyItems:YES];
        }else{
            NSMutableArray *newResult = [[NSMutableArray alloc]initWithArray:userData];
            [newResult addObjectsFromArray:result[@"content"]];
            userData = [[NSMutableArray alloc]initWithArray:newResult copyItems:YES];
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
        }
        _page++;
        isLoading = NO;
        
        if (userData.count < 20){
            isLoading = YES;
        }
        
        reloading = NO;
        [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        [SVProgressHUD dismiss];
        isLoading = YES;
    }];
}
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        CATransition*transition=[CATransition animation];
        transition.duration=1;
        transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type=kCATransitionPush;
        transition.subtype=kCATransitionFromLeft;//方向
        [self.view.layer addAnimation:transition forKey:nil];
        [self popOfDismss];
        //        [self dismissViewControllerAnimated:YES completion:^{
        [SVProgressHUD dismiss];
        //        }];
        
    }
}

-(void)popOfDismss{
    
    
//    if (![self.title isEqualToString:@"咨询"]) {
        //设置通知，显示tabbar
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showBootomBar" object:self userInfo:nil ];
        
//    }
    
    
    if ([[self.navigationController viewControllers] count]>=2) {
        self.hidesBottomBarWhenPushed = NO;
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        self.hidesBottomBarWhenPushed = NO;
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [SVProgressHUD dismiss];
}

#pragma mark - Table view data source
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    if (section==0) {
//        return [self tableHeader];
//    }else{
        return nil;
//    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 
    NSLog(@"[userData count] == %lu",(unsigned long)[userData count]);
    NSLog(@"userData.count == %lu",(unsigned long)userData.count);
    return [userData count];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
 
    if ([self.title isEqualToString:@"游学"]) {
        return 255 ;//
        
    }
    else if ([self.title isEqualToString:@"论坛"]){
    return 240;
    }
    
    else {
        return 260;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
 
        return 0;
 
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell ;
    
    NSDictionary *informationDic = userData[indexPath.row];

    
    if ([self.title isEqualToString:@"游学"]) {
        
        
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"StudyTourCell" forIndexPath:indexPath];
        
        if (cell==nil) {
            
            cell=[tableView dequeueReusableCellWithIdentifier:@"StudyTourCell"];
            
        }
        
        if(indexPath.row == [userData count]-2){
            [SVProgressHUD showWithStatus:@"数据加载中..." maskType:SVProgressHUDMaskTypeClear];
            [self loadNews];
        }
        
        UILabel*label6=(UILabel*)[cell.contentView viewWithTag:66];
        label6.text = @"10人";
        label6.text = [NSString stringWithFormat:@"%@人",[informationDic objectForKey:@"number"]];
        
        
        
        
        NSString *timeString = [informationDic objectForKey:@"inputtime"];
        NSLog(@"timeString -- %@",timeString);
        //得到运动时间，需要转成年月日
        NSString *formatString = @"YYYY-MM-dd";
        
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:formatString];
        NSDate*confromTimesp = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[timeString intValue] - 28800];
        NSString *dateString =[NSString stringWithFormat:@"%@",[dateFormat stringFromDate:confromTimesp] ];
        NSLog(@"date: %@", dateString);
        
        UILabel*label10=(UILabel*)[cell.contentView viewWithTag:10];
 
        label10.text = dateString;//area


        
        UILabel*label4=(UILabel*)[cell.contentView viewWithTag:44];
        
        UIImageView *backImage = (UIImageView *)[cell.contentView viewWithTag:121];
        //        activitystatus	数字	活动状态:1=筹备中,2=进行中,3=已过期
        
        NSString *acc = informationDic[@"activitystatus"];
        int accc = [acc intValue];
        
        switch (accc) {
            case 1:
                label4.text = @"筹备中";
                backImage.image = [UIImage imageNamed:@"going"];
                break;
                
            case 2:
                label4.text = @"进行中";
                backImage.image = [UIImage imageNamed:@"going"];
                break;
                
            case 3:
                label4.text = @"已过期";
                backImage.image = [UIImage imageNamed:@"TimeOut"];
                break;
                
            default:
                break;
        }
        
    }
    
    
    else if ([self.title isEqualToString:@"论坛"]){
        cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell" forIndexPath:indexPath];
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"MainCell"];
        }
    
    
        
            UILabel*label5=(UILabel*)[cell.contentView viewWithTag:55];
            label5.text = @"参与人数：";
            
            UILabel*label7=(UILabel*)[cell.contentView viewWithTag:77];
            label7.text = @"活动时间";
            
            UILabel*label9=(UILabel*)[cell.contentView viewWithTag:88];
            label9.text = @"活动地区";
            
            
            

            
            
            UILabel*label6=(UILabel*)[cell.contentView viewWithTag:66];
            label6.text = @"10人";
            label6.text = [NSString stringWithFormat:@"%@人",[informationDic objectForKey:@"number"]];
            
            
//            UILabel*label8=(UILabel*)[cell.contentView viewWithTag:10];
//            label8.text = @"2015-1-12";
            NSString *timeString = [informationDic objectForKey:@"inputtime"];
            NSLog(@"timeString -- %@",timeString);
            //得到运动时间，需要转成年月日
            NSString *formatString = @"YYYY-MM-dd";
            
            NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
            [dateFormat setDateFormat:formatString];
            NSDate*confromTimesp = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[timeString intValue] - 28800];
            NSString *dateString =[NSString stringWithFormat:@"%@",[dateFormat stringFromDate:confromTimesp] ];
            NSLog(@"date: %@", dateString);
            
            
            
            UILabel*label10=(UILabel*)[cell.contentView viewWithTag:10];
            label10.text = @"重庆";//area
            UILabel*labelcc=(UILabel*)[cell.contentView viewWithTag:88];
            NSLog(@"[informationDic objectForKey:area] -- %@",[informationDic objectForKey:@"area"]);
            labelcc.text = [informationDic objectForKey:@"area"];
//            label9.backgroundColor = [UIColor redColor];
            label10.text = dateString;//area
            
            
            UILabel*label4=(UILabel*)[cell.contentView viewWithTag:44];
            UIImageView *backImage = (UIImageView *)[cell.contentView viewWithTag:121];
            //        activitystatus	数字	活动状态:1=筹备中,2=进行中,3=已过期
            
            NSString *acc = informationDic[@"activitystatus"];
            int accc = [acc intValue];
            
            switch (accc) {
                case 1:
                    label4.text = @"筹备中";
                    backImage.image = [UIImage imageNamed:@"going"];
                    break;
                    
                case 2:
                    label4.text = @"进行中";
                    backImage.image = [UIImage imageNamed:@"going"];
                    break;
                    
                case 3:
                    label4.text = @"已过期";
                    backImage.image = [UIImage imageNamed:@"TimeOut"];
                    break;
                    
                default:
                    break;
            }
        
    }
    
    
    else if ([self.title isEqualToString:@"创投"]){
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"CTCell" forIndexPath:indexPath];
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"CTCell"];
        }
        
        UILabel*label5=(UILabel*)[cell.contentView viewWithTag:55];
        label5.text = @"所属行业:";
        
        UILabel*label7=(UILabel*)[cell.contentView viewWithTag:10];
        label7.text = @"发布时间";
        
        UILabel*label9=(UILabel*)[cell.contentView viewWithTag:99];
        label9.text = @"所在地区";
        
        UILabel*label6=(UILabel*)[cell.contentView viewWithTag:66];
        //            label6.text = @"餐饮";
        label6.text = [informationDic objectForKey:@"typeid"];
        
        NSString *timeString = [informationDic objectForKey:@"inputtime"];
        NSLog(@"timeString -- %@",timeString);
        //得到运动时间，需要转成年月日
        NSString *formatString = @"YYYY-MM-dd";
        
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:formatString];
        NSDate*confromTimesp = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[timeString intValue] - 28800];
        NSString *dateString =[NSString stringWithFormat:@"%@",[dateFormat stringFromDate:confromTimesp] ];
        NSLog(@"date: %@", dateString);
        label7.text = dateString;
        
        UILabel*label10=(UILabel*)[cell.contentView viewWithTag:88];
        //            label10.text = @"重庆";
        label10.text = [informationDic objectForKey:@"area"];
        
        
        
        UILabel*label4=(UILabel*)[cell.contentView viewWithTag:44];
        
        
        //            label4.text = @"融资中";
        //            financingstatus	数字	融资状态:1=融资中,2=已完成
         UIImageView *backImage = (UIImageView *)[cell.contentView viewWithTag:121];
        NSString *acc = informationDic[@"financingstatus"];
        int accc = [acc intValue];
        
        switch (accc) {
            case 1:
                label4.text = @"融资中";
                backImage.image = [UIImage imageNamed:@"going"];
                break;
                
            case 2:
                label4.text = @"已完成";
                 backImage.image = [UIImage imageNamed:@"TimeOut"];
                break;
                
            default:
                break;
        }
        
            UILabel*label3=(UILabel*)[cell.contentView viewWithTag:33];
            label3.text = @"商业模式创新与顶层设计，商业的转型升级战1";
            label3.text = [informationDic objectForKey:@"description"];

    }

    
    UIImageView*imageView=(UIImageView*)[cell.contentView viewWithTag:11];
    [imageView sd_setImageWithURL:[NSURL URLWithString:informationDic[@"thumb"]]];
    
    UILabel*label2=(UILabel*)[cell.contentView viewWithTag:22];
    label2.text = @"商业模式特训营";
    label2.text = [informationDic objectForKey:@"title"];
    
    

   
    cell.backgroundColor = UIColorFromRGB(0xf5f5f5);

 
    
    return cell;
}

    
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    indexPath.row;
       [tableView deselectRowAtIndexPath:indexPath animated:NO];//点击后不会有阴影
    NSDictionary *lunTanDic = userData[indexPath.row];
    NSLog(@"lunTanDic == %@",lunTanDic);
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:lunTanDic forKey:@"lunTanDic"];
    [userDefault synchronize];//存入数据，单例

//    if ([self.title isEqualToString:@"创投"]) {
//        [self performSegueWithIdentifier:@"IWanIdentifier" sender:indexPath];
//    }
//    
//    else if ([self.title isEqualToString:@"游学"]) {
//        [self performSegueWithIdentifier:@"studyTourIdentifer" sender:indexPath];
//    }
//    
//    else if ([self.title isEqualToString:@"论坛"]) {
//        [self performSegueWithIdentifier:@"BBSPushIdentifer" sender:indexPath];
    
    NSString *auth_type = [lunTanDic objectForKey:@"auth_type"];
    BOOL auth_typeBOOL;
    
    
    if([auth_type rangeOfString:@"1"].location !=NSNotFound)//_roaldSearchText
    {
        NSLog(@"yes");
        
        if (auth_type.length > 0) {
            
            NSArray *auth_typeArray = [auth_type componentsSeparatedByString:@","]; //从字符A中分隔成2个元素的数组
            NSLog(@"auth_typeArray:%@",auth_typeArray);
            NSString *groupids_view = [lunTanDic objectForKey:@"groupids_view"];
            NSString *a = [[NSString alloc] init];
            for (a in auth_typeArray) {
                NSLog(@"--a-- %@",a);
                if ([a isEqualToString:groupids_view]) {
                    [self pushToTheNextView];
//                    [self performSegueWithIdentifier:@"pushOneClubeIdentifier" sender:indexPath];
                    
                    

                    return;
                    auth_typeBOOL = NO;
                }
            }
            
            [SVProgressHUD showSuccessWithStatus:@"您没有阅读权限。"];
        }
    }
    else
    {
        
        [self pushToTheNextView];
//        [self performSegueWithIdentifier:@"pushOneClubeIdentifier" sender:indexPath];

        NSLog(@"no");
    }
 
    //    }pushOneClubeIdentifier  pushTheNewClueShow
    
    
}

- (void)pushToTheNextView{
    self.hidesBottomBarWhenPushed = YES;
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginViewController *MainCell=[story instantiateViewControllerWithIdentifier:@"OneClubeViewController"];
    [self.navigationController pushViewController:MainCell animated:YES];
     
}


#pragma mark - UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
    int page = (scrollView.contentOffset.x / scrollView.bounds.size.width);
    NSLog(@"page = %d",page);
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    
}


#pragma mark RefreshHeaderViewDelegate Methods

-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view{
    if(reloading){
        return;
    }
    reloading=YES;
    [self performSelector:@selector(doneLoadingViewData) withObject:nil afterDelay:0];
}
- (void)doneLoadingViewData{
    
    //  model should call this when its done loading
    _page=1;
    isLoading = NO;
    userData = nil;
//    topArray = [[NSMutableArray alloc]init];
    [self loadNews];
    
}
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view{
    return reloading;
}
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view{
    return [NSDate date];
}
#pragma mark - Table view data source


@end
